package com.imau.controller;

import com.imau.bean.User;
import com.imau.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class UserRegisterServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取表单数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 获取 session 中的验证码
        String code = (String) req.getSession().getAttribute("checkCode");

        // 获取用户输入的验证码
        String checkCode = req.getParameter("checkCode");

        // 校验验证码（使用安全的方式进行比较）
        if (checkCode != null && !checkCode.isEmpty() && checkCode.equalsIgnoreCase(code)) {
            // 验证码正确，继续注册逻辑
            boolean b = userService.registerUser(new User(null, username, password));

            if (b) {
                resp.sendRedirect(req.getContextPath() + "/login.html");
            } else {
                resp.sendRedirect(req.getContextPath() + "/register.html");
            }
        } else {
            // 验证码错误或为空
            System.out.println("Session code: " + code);
            System.out.println("Form checkCode: " + checkCode);
            resp.sendRedirect(req.getContextPath() + "/register.html");
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
